<!--
  * @description : 零售户信息列表
  * @descriptionDetail : 零售户信息列表 
  * @author : zx-广西零售户编辑列表-GX（广西不需要分值、档位）
  * @create : 2024-3-12 00:00:00
-->
<template>
  <view class="page">
    <!-- #ifdef H5-ONLY -->
    <!-- 零售户查询功能中，查询条件中档位查询可选多个档位需要改成单选，档位选择框点确定后弹窗不能自动消失 找祝肖  2024-4-17   start-->
    <theme-navbar :is-white="false" backText="返回" title="零售户列表" :custom-back="goBack">
      <view class="nav-right-icon">
        <u-icon name="list" color="#FFF" size="38" style="margin: 0 14rpx 0 6rpx" @tap="orgShow = true"></u-icon>
      </view>
    </theme-navbar>
    <!-- #ifdef H5-WECHAT || H5-EMP -->
    <fab-button :content="fContent" @fabtrigger="fabtrigger" />
    <!-- #endif -->
    <!-- #endif -->
    <view class="content-list">
      <me-table :i="0" :top="108" :index="0" :load-data="loadData" :init-load="false" ref="mescrollItem0">
        <view class="re-list" slot-scope="d">
          <u-swipe-action :index="d.index"  :show="contentList[d.index].showSwipe" @click="deliverClick" @open="deliverOpen" :options="cardOptions">
           <view class="re-content" >
            <view class="re-manager" @click="viewRetailerDetail(d.data)">
              <text class="re-title">{{ d.data.companyName }}</text>
              <u-tag style="flex-shrink: 0; height: fit-content;margin-right: 5px" :spStyle="getSpStyle(d.data)" v-if="d.data.licStatus" mode="dark" shape="circle" :text="d.data.licStatusName"></u-tag>
              <text class="re-tit"></text>
            </view>
            <view class="re-subtitle">{{ d.data.businessAddr }}</view>
            <view class="re-icon">
              <u-row>
                <u-col span="6" style="padding-left: 0px">
                  <u-icon :label="d.data.managerName || ''" size="30" name="/static/check/manager.png"></u-icon>
                </u-col>
                <u-col span="6">
                  <u-icon :label="d.data.retailTel || ''" size="30" name="phone" @click="modelConfirm(d.data.retailTel)"></u-icon>
                </u-col>
              </u-row>
            </view>
            
          </view>
          </u-swipe-action>
          <!-- 提示框 modelContent -->
            <u-modal v-model="modelShow" :content="modelContent" @confirm="doPhoneNew(d.data.retailTel)"></u-modal>
        </view>
      </me-table>
    </view>
    <u-popup v-model="orgShow" width="80%" mode="right">
      <view class="cearch_title">查询条件</view>
      <u-form :model="orgForm" label-position="top" label-width="auto" style="padding: 80rpx 32rpx 160rpx 32rpx" ref="orgForm">
        <u-form-item label="模糊匹配:">
          <u-input placeholder="许可证、企业字号、持证人、地址、电话等" v-model="orgForm.keyWord" />
        </u-form-item>
        <u-form-item label="信用等级:" prop="creditLevel">
          <u-input placeholder="请选择信用等级" v-model="orgForm.creditLevel" @click="showCreditLevel = true" />
          <u-action-sheet :list="creditLevelList" v-model="showCreditLevel" @click="handleCreditLevel"></u-action-sheet>
        </u-form-item>
        <!-- <u-form-item label="分值:">
          <u-input type="number" placeholder="请输入" v-model="orgForm.creditScoreBegin"></u-input>
          <text class="txt-sty">-</text>
          <u-input type="number" placeholder="请输入" v-model="orgForm.creditScoreEnd"></u-input>
        </u-form-item>
        <u-form-item label="档位:">
          <dic-input :keyWord="$u.dic.DIC_KEYS.I_CUST_TYPE_LEVEL" :dicCode="searchObj.custTypeCode" inputAlign="left" type="select"
            :select-open="dicSelectOpen('custTypeCode',$u.dic.DIC_KEYS.I_CUST_TYPE_LEVEL,'1')" placeholder="请选择" v-model="searchObj.custTypeName"
            @changeInputModelData="(name)=>{$set(searchObj, 'custTypeName', name)}" @click="showDic($u.dic.DIC_KEYS.I_CUST_TYPE_LEVEL, searchObj.custTypeCode, 'custTypeCode')" />
        </u-form-item> -->
        <u-form-item label="行政区划:">
          <u-input placeholder="请选择行政区划" v-model="searchObj.regionalization" @click="showRegionalization = true" />
        </u-form-item>
        <u-form-item label="片区:">
          <u-input placeholder="请选择片区" v-model="searchObj.areaName" @click="showOrgSelect = true" />
        </u-form-item>
        <u-form-item label="制证时间:">
          <u-input placeholder="请选择制证时间" v-model="searchObj.accrediDate" @click="showAccrediDate = true" />
          <u-calendar v-model="showAccrediDate" mode="range" @change="changeAccrediDate"></u-calendar>
        </u-form-item>
        <u-form-item label="许可证状态:">
          <dic-input :keyWord="$u.dic.DIC_KEYS.L_LIC_STATUS" :dicCode="searchObj.licStatusCode" inputAlign="left" type="select"
            :select-open="dicSelectOpen('licStatusCode',$u.dic.DIC_KEYS.L_LIC_STATUS)" placeholder="请选择" v-model="searchObj.licStatusName"
            @changeInputModelData="(name)=>{$set(searchObj, 'licStatusName', name)}" @click="showDic($u.dic.DIC_KEYS.L_LIC_STATUS, searchObj.licStatusCode, 'licStatusCode')" />
        </u-form-item>
      </u-form>
      <view class="submit-btns btn-other-cls">
        <u-button plain class="del" type="primary" @click="reset">重置</u-button>
        <u-button class="mit" type="primary" @click="selectChange">确定</u-button>
      </view>
    </u-popup>
    <!-- 行政区划选择 -->
    <u-popup mode="bottom" height="80%" v-model="showRegionalization">
      <area-select @choose="regionalizationConfirm"></area-select>
    </u-popup>
    <!-- 片区选择 -->
    <u-popup mode="bottom" height="80%" v-model="showOrgSelect">
      <org-select tips="请选择片区" treeType="zm-all" @choose="handlerChooseOrg"></org-select>
    </u-popup>
    <u-popup mode="bottom" height="50%" v-model="dicShow">
      <dic-multi-choice :keyWord="dicKeyWords" :defaultUids="dicCurrentSelect" @select="selectDicConfirm" :otherLogic="isOtherLogic" :logicFun="logicFun"></dic-multi-choice>
    </u-popup>
  </view>
</template>

<script>
import MeTable from "@/components/me-table.vue";
import { AMapMixin } from "@/common/AMapMixin.js";
import dicInput from "@/components/dic_input.vue";
import orgSelect from "@/components/org-select.vue";
import areaSelect from "@/components/area-select.vue";
import dicMultiChoice from "@/components/dic_multi_choice.vue";
import MescrollMoreMixin from "@/components/mescroll-uni/mixins/mescroll-more.js";
import certificateService from "@/service/certificate/certificate.service.js";
import checkService from "@/service/check/check.service";
import { L_LIC_STATUS } from "@/service/query/mapping/enum.js";
import { SET_MAP_LAT_LON } from "@/config/setting.config.js";
	import {
		dateUtils,
	} from "@/common/util";
const sysCodeColors = {
  "07": {
    color: "#EC7C37",
    borderColor: "#EC7C37",
    backgroundColor: "#FBE2D3"
  },
  "04": {
    color: "#01A79A",
    borderColor: "#01A79A",
    backgroundColor: "#C0ECE2"
  },
  "01": {
    color: "#AC0000",
    borderColor: "#AC0000",
    backgroundColor: "#F2CCCC"
  },
  "06": {
    color: "#FF9E2C",
    borderColor: "#FF9E2C",
    backgroundColor: "#FFF3E6"
  },
  "08": {
    color: "#0079F2",
    borderColor: "#0079F2",
    backgroundColor: "#E0ECFF"
  },
  "02": {
    color: "#717579",
    borderColor: "#717579",
    backgroundColor: "#EDEEEF"
  },
  "05": {
    color: "#20AB5C",
    borderColor: "#20AB5C",
    backgroundColor: "#DBF4E6"
  },
  "03": {
    color: "#FF9E2C",
    borderColor: "#FF9E2C",
    backgroundColor: "#FFF3E6"
  }
};
export default {
  components: { MeTable, areaSelect, orgSelect, dicInput, dicMultiChoice },
  mixins: [MescrollMoreMixin, AMapMixin],
  data() {
    return {
      dicShow: false,
      orgShow: false,
      showOrgSelect: false,
      showCreditLevel: false,
      showAccrediDate: false,
      showRegionalization: false,
      modelShow: false,
      modelContent: "",
      longitude: "",
      latitude: "",
      tels: [],
      user: this.$storage.get(this.$rp.common.USER),
      retailData: [],
      firstNoLoad: false,
      dicType: "",
      dicKeyWords: "",
      dicCurrentSelect: "",
      searchObj: {
        areaName: "",
        accrediDate: "",
        custTypeName: "",
        custTypeCode: "",
        licStatusName: "",
        licStatusCode: "",
        regionalization: ""
      },
      creditLevelList: [
        { text: "AAA" },
        { text: "AA" },
        { text: "A" },
        { text: "B" },
        { text: "C" },
        { text: "D" }
      ],
      fContent: [
        {
          iconPath: require("@/static/sou.png"),
          selectedIconPath: require("@/static/sou.png"),
          text: "筛选",
          active: false
        }
      ],
      orgForm: {
        keyWord: "", // 关键字
        creditLevel: "", // 信用等级
        creditScoreBegin: "", // 信用分值_起
        creditScoreEnd: "", // 信用分值_止
        regionalization: "", // 行政区划
        custTypeName: "", // 档位
        orgUuid: "", // 片区
        accrediDateBegin: "", // 制证时间_开始
        accrediDateEnd: "", // 制证时间_结束
        licStatus: [] // 许可证状态
      },
      isOtherLogic: false,
      currentType: "",
      currentKeyWords: "",
      cardOptions: [
        {
          text: "编辑",
          style: {
            backgroundColor: "#007aff"
          }
        },
        // {
        //   text: "删除",
        //   style: {
        //     backgroundColor: "#dd524d"
        //   }
        // }
      ],
      contentList: [],
    };
  },
  mounted() {
    this.setRightBtns();
  },
  methods: {
    setRightBtns() {
      // #ifdef H5-DINGDING
      this.$deviceApi.setRight(
        "筛选",
        () => {
          this.orgShow = true;
          this.setRightBtns();
        },
        true,
        true
      );
      // #endif
    },
    fabtrigger(btn) {
      if (btn.index == 0) {
        this.orgShow = true;
      }
    },
    selectChange() {
      this.orgShow = false;
      this.$refs["mescrollItem0"].refresh();
    },
    reset() {
      this.orgForm = {};
      for (let i in this.searchObj) {
        this.searchObj[i] = "";
      }
    },
    handleCreditLevel(index) {
      this.orgForm.creditLevel = this.creditLevelList[index].text;
      this.showCreditLevel = false;
    },
    regionalizationConfirm(areas) {
      this.orgForm.regionalization = areas[0].areaCode;
      this.searchObj.regionalization = `${areas[0].proName}${areas[0].admdivName}${areas[0].countryName}`;
      this.showRegionalization = false;
    },
    handlerChooseOrg(orgs) {
      this.searchObj.areaName = orgs[0].name;
      this.orgForm.orgUuid = orgs[0].id;
      this.showOrgSelect = false;
    },
    changeAccrediDate(e) {
      this.orgForm.accrediDateBegin = e.startDate;
      this.orgForm.accrediDateEnd = e.endDate;
      this.searchObj.accrediDate = `${e.startDate} - ${e.endDate}`;
    },
    dicSelectOpen(type, keyWords, flag) {
      console.log(type);
      if (type == this.dicType) {
        if (this.dicKeyWords == keyWords && this.dicShow) {
          if (flag) {
            this.isOtherLogic = true;
          } else {
            this.isOtherLogic = false;
          }
          return true;
        }
        return false;
      }
    },
    showDic(key, cur, type) {
      if (this.dicShow) return;
      this.dicKeyWords = key;
      this.dicCurrentSelect = cur;
      this.dicShow = true;
      this.dicType = type;
    },
    selectDicConfirm(e) {
      const codes = e.map(item => item.bcbCode);
      const label = e.map(item => item.bcbName).join(",");
      if (this.dicKeyWords == this.$u.dic.DIC_KEYS.L_LIC_STATUS) {
        // 许可证状态
        this.searchObj.licStatusName = label;
        this.searchObj.licStatusCode = codes.join(",");
        this.orgForm.licStatus = codes;
      } else if (this.dicKeyWords == this.$u.dic.DIC_KEYS.I_CUST_TYPE_LEVEL) {
        // 客户分类
        this.searchObj.custTypeName = label;
        this.searchObj.custTypeCode = codes.join(",");
        this.orgForm.custTypeName = label;
      }
      this.dicShow = false;
    },
    initAmap() {},
    getSpStyle(it) {
      if (it.licStatus == L_LIC_STATUS.SHUT_STATUS) {
        return sysCodeColors[it.licStatus] || {};
      } else if (it.licStatus == L_LIC_STATUS.ORDER_SHUT_STATUS) {
        return sysCodeColors[it.licStatus] || {};
      } else if (it.licStatus == L_LIC_STATUS.CANCEL_STATUS) {
        return sysCodeColors[it.licStatus] || {};
      } else if (it.licStatus == L_LIC_STATUS.CLOSE_STATUS) {
        return sysCodeColors[it.licStatus] || {};
      } else if (it.licStatus == L_LIC_STATUS.WITHDRAW_STATUS) {
        return sysCodeColors[it.licStatus] || {};
      } else if (it.licStatus == L_LIC_STATUS.REVOKE_STATUS) {
        return sysCodeColors[it.licStatus] || {};
      } else if (it.licStatus == L_LIC_STATUS.RECALL_STATUS) {
        return sysCodeColors[it.licStatus] || {};
      } else if (it.licStatus == L_LIC_STATUS.NORMAL_STATUS) {
        return sysCodeColors[it.licStatus] || {};
      }
    },
    // 零售户列表数据查询
    loadData(page) {
      if (!this.orgForm.licStatus || this.orgForm.licStatus.length === 0) {
        this.orgForm.licStatus = ["01", "02", "10"];
      }
      return new Promise(resolve => {
        this.longLatit().then(() => {
          certificateService
            .getRetailerListByApp(page.num, page.size, this.orgForm)
            .then(res => {
              if (res.success) {
                let list = res.data.map(item => {
                return {
                  ...item,
                  showSwipe: false
                };
              });
              this.contentList = this.contentList.concat(list);
                resolve({
                  count: res.count,
                  // data: [...res.data],
                  data: [...list]
                });
              } else {
                resolve({
                  count: 0,
                  data: []
                });
              }
            })
            .catch(e => {
              resolve({
                count: 0,
                data: []
              });
            });
        });
      });
    },
    longLatit() {
      let self = this;
      return new Promise(resolve => {
        if (this.$deviceApi.geolocation) {
          this.$deviceApi.geolocation().then(res => {
            self.longitude = res.longitude;
            self.latitude = res.latitude;
            resolve();
          });
        } else {
          self.longitude = SET_MAP_LAT_LON[0];
          self.latitude = SET_MAP_LAT_LON[1];
          resolve();
        }
      });
    },
    // 查看零售户详情
    viewRetailerDetail(retailer) {
      this.$u.route("pages/retailer/retailerInfo/retailerInfo", {
        retailerUuid: retailer.retailerUuid
      });
    },
    // 电话显示
    handlerShowPhone(e, retailerUuid) {
      this.$u.loading("查询中...");
      this.tels = [];
      checkService.retailerTels(retailerUuid).then(dr => {
        this.$u.hideLoading();
        if (dr.success) {
          let telDatas = dr.data;
          telDatas.forEach(t => {
            t.tel && this.tels.push(t.name + " " + t.tel);
          });
          uni.showActionSheet({
            itemList: this.tels,
            itemColor: "#007aff",
            success: ({ tapIndex }) => this.doPhone(this.tels[tapIndex])
          });
        }
      });
    },
    // 拨打电话
    doPhone(telStr) {
      let tel = telStr.substring(telStr.indexOf(" "));
      this.$deviceApi.makePhoneCall(tel);
    },
    // 拨打电话
    doPhoneNew(telStr) {
      if (this.$u.test.isEmpty(telStr)) return;
      // #ifdef H5-DINGDING
      this.$deviceApi.makePhoneCall(telStr);
      // #endif
      // #ifndef H5-DINGDING
      this.$u.toast("H5不支持打电话");
      // #endif
    },
    modelConfirm() {
      this.modelShow = true;
      this.modelContent = "是否打给零售户";
    },
    // 信用档位互斥逻辑函数
    logicFun(item, selectedItems) {
      if (this.isOtherLogic) {
        // console.log(selectedItems)
        // debugger
        if (selectedItems.length > 0) {
          selectedItems=[]
          selectedItems.push(item)
          return selectedItems;
        } else {
          selectedItems.push(item);
          return selectedItems;
        }
      }
    },
    deliverClick(index, btnIndex) {
      let list = this.$refs.mescrollItem0.listDatas;
      let processStatus = list[index].status;
      this.deliverOpen(99999); // 无论编辑还是删除 都关闭swipe
      if (btnIndex == 0) {
        // if (processStatus == "00") {
          this.$u.route(
            "pages/query/editRetailer/components/editRetailerInfo",
            {
              retailerUuid: list[index].retailerUuid,
              licNo: list[index].licNo
            }
          );
        // } else {
        //   this.$u.toast("当前处于非草稿状态下，不可编辑");
        // }
      }
      //  else {
      //   // 可以删除
      //   if (processStatus == "00") {
      //     // let params = [list[index].id];
      //     this.$modal.confirm("确定要删除吗?", () => {
      //       checkService
      //         .deleteCreditRepairRecord({
      //           repairRecordUuid: list[index].repairRecordUuid
      //         })
      //         .then(res => {
      //           if (res.success) {
      //             this.$modal.alert("删除成功");
      //             this.loadData({ num: "1", size: "10" });
      //             this.$refs["mescrollItem0"].refresh();
      //           } else {
      //             this.$modal.alert(res.msg);
      //           }
      //         })
      //         .catch(err => {
      //           this.$modal.alert("删除失败");
      //         });
      //     });
      //   } else {
      //     this.$u.alert("当前处于非草稿状态下，不可删除");
      //   }
      // }
    },
    updateBackState(param) {
      if (param.SaveRefresh) {
        this.$modal.alert("保存成功");
      }
    },
    deliverOpen(index) {
      this.contentList[index] ? (this.contentList[index].showSwipe = true) : "";
      this.contentList.map((val, idx) => {
        if (index != idx) this.contentList[idx].showSwipe = false;
      });
    },
  }
};
</script>

<style lang="scss" scoped>
@import "style/certificate/common.scss";
.page {
  padding: 0;
}
.content-list {
  background-color: #f3f4f5;
}
.nolicence-search-lay {
  background-color: #fff;
  position: fixed;
  // #ifndef H5-DINGDING
  top: 44px;
  // #endif
  // #ifdef H5-DINGDING
  top: 0px;
  // #endif
  z-index: 999;
  width: 100%;
  overflow: hidden;
  padding: $cm-search-padding-row $cm-search-padding-column;
}
.re-list {
  margin: 20rpx;
  color: #666666;
  font-size: 15px;
  border-bottom: 1px solid #e9e9e9;
  // display: flex;
  // flex-direction: row;
  // justify-content: flex-start;
  // -webkit-flex-direction: row;
  background-color: #fff;
  border-radius: 12px;
  padding: 12px 10px;
  // overflow: hidden;
}
.re-media {
  padding-right: 10px;
  vertical-align: middle;
}
.re-content {
  width: 100%;
  .re-manager {
    display: flex;
    justify-content: space-between;
    .re-title {
      width: calc(90%);
      font-size: 15px;
      color: #666;
      font-weight: 600;
      margin-bottom: 5px;
      width: 80%;
    }
  }
  .re-subtitle {
    padding-top: 5px;
    color: #666;
  }
  .re-icon {
    display: flex;
    padding-top: 10px;
  }
}
/deep/.u-line {
  flex-shrink: 0;
}
.cearch_title {
  background-color: #f3f4f5;
  width: 100%;
  height: 82rpx;
  font-size: 32rpx;
  font-weight: 600;
  padding: 22rpx 0 21rpx 32rpx;
  z-index: 999;
  position: fixed;
}
.txt-sty {
  line-height: 60rpx;
  padding: 0 10px;
}
/deep/ .mescroll-body {
  padding-top: 0px !important;
}
// 零售户查询功能中，查询条件中档位查询可选多个档位需要改成单选，档位选择框点确定后弹窗不能自动消失 找祝肖
</style>
